﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using PublisherManagementSystem.DAL;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using PublisherManagementSystem.Models;

namespace PublisherManagementSystem.Controllers
{
    public class PublishersController : Controller
    {
        private readonly PublisherDbContext _context;

        public PublishersController(PublisherDbContext context)
        {
            _context = context;
        }

        // GET: Publishers
        public async Task<IActionResult> Index()
        {
            var publisherManagementSystemContext = _context.Publishers.Include(p => p.City).Include(p => p.District).Include(p => p.Province);
            return View(await publisherManagementSystemContext.ToListAsync());
        }

        // GET: Publishers/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var publisher = await _context.Publishers
                .Include(p => p.City)
                .Include(p => p.District)
                .Include(p => p.Province)
                .FirstOrDefaultAsync(m => m.PublisherID == id);
            if (publisher == null)
            {
                return NotFound();
            }

            return View(publisher);
        }

        // GET: Publishers/Create
        public IActionResult Create()
        {
            ViewData["CityID"] = new SelectList(_context.Set<City>(), "CityID", "CityName");
            ViewData["DistrictID"] = new SelectList(_context.Set<District>(), "DistrictID", "DistrictName");
            ViewData["ProvinceID"] = new SelectList(_context.Set<Province>(), "ProvinceID", "ProvinceName");
            return View();
        }

        // POST: Publishers/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("PublisherID,PublisherName,ProvinceID,CityID,DistrictID,Address,ContactPerson,Phone,Email")] Publisher publisher)
        {
            if (ModelState.IsValid)
            {
                _context.Add(publisher);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["CityID"] = new SelectList(_context.Set<City>(), "CityID", "CityName", publisher.CityID);
            ViewData["DistrictID"] = new SelectList(_context.Set<District>(), "DistrictID", "DistrictName", publisher.DistrictID);
            ViewData["ProvinceID"] = new SelectList(_context.Set<Province>(), "ProvinceID", "ProvinceName", publisher.ProvinceID);
            return View(publisher);
        }

        // GET: Publishers/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var publisher = await _context.Publishers.FindAsync(id);
            if (publisher == null)
            {
                return NotFound();
            }
            ViewData["CityID"] = new SelectList(_context.Set<City>(), "CityID", "CityName", publisher.CityID);
            ViewData["DistrictID"] = new SelectList(_context.Set<District>(), "DistrictID", "DistrictName", publisher.DistrictID);
            ViewData["ProvinceID"] = new SelectList(_context.Set<Province>(), "ProvinceID", "ProvinceName", publisher.ProvinceID);
            return View(publisher);
        }

        // POST: Publishers/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("PublisherID,PublisherName,ProvinceID,CityID,DistrictID,Address,ContactPerson,Phone,Email")] Publisher publisher)
        {
            if (id != publisher.PublisherID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(publisher);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PublisherExists(publisher.PublisherID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["CityID"] = new SelectList(_context.Set<City>(), "CityID", "CityName", publisher.CityID);
            ViewData["DistrictID"] = new SelectList(_context.Set<District>(), "DistrictID", "DistrictName", publisher.DistrictID);
            ViewData["ProvinceID"] = new SelectList(_context.Set<Province>(), "ProvinceID", "ProvinceName", publisher.ProvinceID);
            return View(publisher);
        }

        // GET: Publishers/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var publisher = await _context.Publishers
                .Include(p => p.City)
                .Include(p => p.District)
                .Include(p => p.Province)
                .FirstOrDefaultAsync(m => m.PublisherID == id);
            if (publisher == null)
            {
                return NotFound();
            }

            return View(publisher);
        }

        // POST: Publishers/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var publisher = await _context.Publishers.FindAsync(id);
            if (publisher != null)
            {
                _context.Publishers.Remove(publisher);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool PublisherExists(int id)
        {
            return _context.Publishers.Any(e => e.PublisherID == id);
        }
        // AJAX方法：根据省份获取城市
        [HttpGet]
        public JsonResult GetCitiesByProvince(int provinceId)
        {
            var Cities = _context.Set<City>()
                .Where(c => c.ProvinceID == provinceId)
                .Select(c => new { c.CityID, c.CityName })
                .ToList();

            return Json(Cities);
        }

        // AJAX方法：根据城市获取区县
        [HttpGet]
        public JsonResult GetDistrictsByCity(int cityId)
        {
            var Districts = _context.Set<District>()
                .Where(d => d.CityID == cityId)
                .Select(d => new { d.DistrictID, d.DistrictName })
                .ToList();

            return Json(Districts);
        }
    }
}
